package 链表和树.链表;
//Java：K 个一组翻转链表
public class ReverseNodesInKGroup{
    public static void main(String[] args) {
        Solution solution = new ReverseNodesInKGroup().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
//    public class ListNode {
//        int val;
//        ListNode next;
//        ListNode() {}
//        ListNode(int val) { this.val = val; }
//        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
//    }
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        //相比于就是多了需要根据链表的长度进行判断是否可以翻转然后不需要遍历找前一个节点了
        //统计
        int n = 0;
        ListNode count = head;
        while(count != null){
            n++;
            count = count.next;
        }
        ListNode dummy = new ListNode(0, head);
        ListNode p0 =dummy;
        ListNode pre = null;
        ListNode cur= head;

        for(;n>=k; n-=k){
            for (int i = 0; i < k; i++){
                ListNode nxt = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nxt;
            }
            //关键点下一个翻转的前一个位置就是未翻转前的p0.next
            //先用p0改好链接再移动p0
            ListNode nxt = p0.next;
            p0.next.next = cur;
            p0.next = pre;
            //最后再移动p0
            p0 = nxt;
        }
        return dummy.next;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}